package com.wty.swhn.wty.view;

import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewConfiguration;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.jivesoftware.smack.Roster;
import org.xbill.DNS.tests.primary;

import com.wty.swhn.wty.R;
import com.wty.swhn.wty.R.id;
import com.wty.swhn.wty.R.menu;
import com.wty.swhn.wty.TApplication;
import com.wty.swhn.wty.adapter.MainFragmentAdapter;
import com.wty.swhn.wty.biz.AddBroadCastBiz;
import com.wty.swhn.wty.biz.fragment.ChangeColorIconWithText;
import com.wty.swhn.wty.util.Const;
import com.wty.swhn.wty.view.fragment.FourFragment;
import com.wty.swhn.wty.view.fragment.MyFriendFragment;
import com.wty.swhn.wty.view.fragment.OneFragment;
import com.wty.swhn.wty.view.fragment.ThreeFragment;

/**
 * Created by swhn on 2016/8/7.
 * 底部按键
 */
public class TopickActivity extends FragmentActivity implements OnPageChangeListener {
	/**
	 * ATTENTION: This was auto-generated to implement the App Indexing API. See
	 * https://g.co/AppIndexing/AndroidStudio for more information.
	 */
	private ViewPager viewPager;
	private OneFragment oneFragment;
	private MyFriendFragment twoFragment;
	private ThreeFragment threeFragment;
	private FourFragment fourFragment;
	ArrayList<Fragment> list;
	MenuA menuA;
	private int index;
	private long exitTime = 0;
	private final static String TAG = "TopickActivity";
	private List<ChangeColorIconWithText> tbInstands = new ArrayList<ChangeColorIconWithText>();
	ChangeColorIconWithText[] but = new ChangeColorIconWithText[4];
	// 用于别的Activity关闭 本Activity
	public static TopickActivity instance = null;
	private AddBroadCastBiz receiver;// 添加好友广播接收器
	private IntentFilter filter, filterN, requese, refuse,isfriend;// 广播监听器

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.topicac);
		setOverFlowButtonAlways();
		instance = this;
		getActionBar().setDisplayShowHomeEnabled(false);
		// 初始化数据

		setupView();
		setDate();
		upderButtonTextCloor();// ===================================2
		menuA = new MenuA(this);
		setReceiverBroadCast();
	}

	private void setReceiverBroadCast() {
		receiver = new AddBroadCastBiz(TopickActivity.this);
		requese = new IntentFilter(Const.REQUESE_ADDFRIEND_OK);// 请求添加对方为好友
		filter = new IntentFilter(Const.ADD_ADDFRIEND_CONSENT);
		filterN = new IntentFilter(Const.ADD_ADDFRIEND_DEL_CONSENT);//删除好友
		refuse = new IntentFilter(Const.REFUSE_ADDFRIEND);// 拒绝对方的添加请求
		isfriend = new IntentFilter(Const.ADDFRIEND_IS_OK);// 已是好友
		this.registerReceiver(receiver, requese);
		this.registerReceiver(receiver, filter);
		this.registerReceiver(receiver, filterN);
		this.registerReceiver(receiver, refuse);
		this.registerReceiver(receiver, isfriend);
	}

	private void setDate() {
		// TODO Auto-generated method stub
		oneFragment = new OneFragment();
		twoFragment = new MyFriendFragment();
		threeFragment = new ThreeFragment();
		fourFragment = new FourFragment();

		list = new ArrayList<Fragment>();
		list.add(oneFragment);// ====若两个相加相同会出现或没有创建对象会出现-IllegalStateException，一般出现这个错误都是在这个地方，加载出了问题
		list.add(twoFragment);
		list.add(threeFragment);
		list.add(fourFragment);
		MainFragmentAdapter adatper = new MainFragmentAdapter(getSupportFragmentManager(), list);
		viewPager.setAdapter(adatper);
	}

	private void setupView() {
		this.viewPager = (ViewPager) findViewById(R.id.id_viewpager);
		ChangeColorIconWithText one = (ChangeColorIconWithText) findViewById(R.id.id_indicator_one);
		tbInstands.add(one);

		ChangeColorIconWithText two = (ChangeColorIconWithText) findViewById(R.id.id_indicator_two);
		tbInstands.add(two);

		ChangeColorIconWithText three = (ChangeColorIconWithText) findViewById(R.id.id_indicator_three);
		tbInstands.add(three);

		ChangeColorIconWithText four = (ChangeColorIconWithText) findViewById(R.id.id_indicator_four);
		tbInstands.add(four);
		// viewPager中的Fragment滑动监听器
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				// TODO Auto-generated method stub
				index = arg0;
				upderButtonTextCloor();// ==============================3滑动fragment底部按钮作相应变化
				Log.i("TAG", "index=========" + index);

			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub

			}
		});

		OnClickListener listener = new setOnClickListener();
		one.setOnClickListener(listener);
		two.setOnClickListener(listener);
		three.setOnClickListener(listener);
		four.setOnClickListener(listener);
	}

	private class setOnClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			chickTb(v);

		}

	}

	private void setOverFlowButtonAlways() {

		try {
			// 反射方法
			/*
			 * ViewConfiguration这个类主要定义了UI中所使用到的标准常量，像超时、尺寸、距离，
			 * 如果我们需要得到这些常量的数据，我们就可以通过这个类来获取，具体方法如下：
			 * 
			 * 1、获取ViewConfiguration对象，
			 * 由于ViewConfiguration的构造方法为私有的，只能通过这个静态方法来获取到该对象。
			 * 
			 * ViewConfiguration configure = ViewConfiguration.get(context);
			 * 
			 * 2、通过该对象调用相关的函数，将返回相关的常量数据。
			 */
			ViewConfiguration config = ViewConfiguration.get(this);
			Field menuKey = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
			menuKey.setAccessible(true);
			// 不显示左上角图标（icon）反射
			menuKey.setBoolean(config, false);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void chickTb(View v) {
		// TODO Auto-generated method stub

		resetOhterTabs();
		switch (v.getId()) {
		case R.id.id_indicator_one:
			index = 0;
			Log.i("TopickActivity", "0=============");
			break;
		case R.id.id_indicator_two:
			index = 1;
			Log.i("TopickActivity", "1=============");
			break;
		case R.id.id_indicator_three:
			index = 2;
			Log.i("TopickActivity", "2=============");
			break;
		case R.id.id_indicator_four:
			index = 3;
			Log.i("TopickActivity", "3=============");
			break;

		}

		viewPager.setCurrentItem(index);
		upderButtonTextCloor();// ======================3底部按钮变化fragment作相应变化

	}

	/**
	 * 重置其他的TabIndicator的颜色
	 */
	private void resetOhterTabs() {
		// TODO Auto-generated method stub
		for (int i = 0; i < tbInstands.size(); i++) {
			tbInstands.get(i).setIconAlpha(0);
		}
	}

	@Override
	public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
		// Log.e("TAG", "position = " + position + " ,positionOffset = "
		// + positionOffset);
		if (positionOffset > 0) {
			ChangeColorIconWithText left = tbInstands.get(position);
			ChangeColorIconWithText right = tbInstands.get(position + 1);
			left.setIconAlpha(1 - positionOffset);
			right.setIconAlpha(positionOffset);
		}

	}

	// 菜单项Menu事件处理方法
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onMenuOpened(int featureId, Menu menu) {
		if (featureId == Window.FEATURE_ACTION_BAR && menu != null) {
			if (menu.getClass().getSimpleName().equals("MenuBuider")) {
				try {
					// 反射
					Method method = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
					method.setAccessible(true);
					method.invoke(menu, true);// 反射设置可调用
				} catch (Exception e) {
					e.printStackTrace();
				}

			}

		}
		return super.onMenuOpened(featureId, menu);
	}

	@Override
	public void onPageSelected(int position) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPageScrollStateChanged(int state) {
		// TODO Auto-generated method stub

	}

	private void upderButtonTextCloor() {
		for (int i = 0; i < tbInstands.size(); i++) {
			if (i == index) {
				tbInstands.get(i).setIconAlpha(1.0f);
			} else {
				tbInstands.get(i).setIconAlpha(0);
			}
		}
	}

	@Override
	public boolean onOptionsItemSelected(android.view.MenuItem item) {
		switch (item.getItemId()) {
		// 添加好友
		case R.id.action_add_friend:
			sendIntent(AddFriendActivity.class);
			break;

		}
		return super.onOptionsItemSelected(item);

	};

	private void sendIntent(Class cls) {
		Intent intent = new Intent(TopickActivity.this, cls);
		startActivity(intent);
	}

	// 按返回按钮提示再按一次退出程序
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
			if ((System.currentTimeMillis() - exitTime) > 2000) {
				Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
				exitTime = System.currentTimeMillis();
			} else {
				TApplication.instance.exit();
				System.exit(0);
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(receiver);
	}
}
